﻿using System.Security.Cryptography.X509Certificates;

namespace MyCSharpWork5
{
    /// <summary>
    ///最小二乘法预测GDP
    /// </summary>
    internal class Program
    {
        static void Main(string[] args)
        {
            //放入数据
            int count = 15;
            List<Year> yearList = new List<Year>();
            yearList.Add(new Year() { x=2021, y =17.7340 });
            yearList.Add(new Year() { x=2020, y =14.6876 });
            yearList.Add(new Year() { x=2019, y =14.2799 });
            yearList.Add(new Year() { x=2018, y =13.8948 });
            yearList.Add(new Year() { x=2017, y =12.3104 });
            yearList.Add(new Year() { x=2016, y =11.2332 });
            yearList.Add(new Year() { x=2015, y =11.0616 });
            yearList.Add(new Year() { x=2014, y =10.4757 });
            yearList.Add(new Year() { x=2013, y =9.5704 });
            yearList.Add(new Year() { x=2012, y =8.5322 });
            yearList.Add(new Year() { x=2011, y =7.5515 });
            yearList.Add(new Year() { x=2010, y =6.0871 });
            yearList.Add(new Year() { x=2009, y =5.1017 });
            yearList.Add(new Year() { x=2008, y =4.5943 });
            yearList.Add(new Year() { x=2007, y =3.5503 });     
            //求x,y平均值
            double totalX = 0, averageX = 0;
            double totalY = 0, averageY = 0;
            foreach (var years in yearList)
            {
                totalX+=years.x;
                totalY+=years.y;
            }
            averageX = totalX/count;
            averageY = totalY/count;
            //求b
            double denominator = 0, numerator = 0;
            foreach (var years in yearList)
            {
                denominator+=(years.x-averageX)*(years.y-averageY);
                numerator+=Math.Pow(years.x-averageX, 2.0);
            }
            double b = denominator/numerator;
            //求a
            double a = averageY-b*averageX;
            //预测
            Console.WriteLine($"线性预测模型为：y={a}+{b}*x");
            double forecast2021 = a+b*2021;
            Console.WriteLine($"预测2021年GDP为{forecast2021}");
            //预测结果
            double GDP2021 = 17.7341;
            double error = (GDP2021-forecast2021)/GDP2021;
            if (error > 0.05||error<-0.05)
                Console.WriteLine($"线性预测模型失败,误差为{error}");
            else Console.WriteLine($"线性预测模型成功{error}");
            Console.ReadKey();
        }
        public class Year
        {
            public double x { get; set; }
            public double y { get; set; }
        }
    }
}